<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $uri = $request->getUri();
        $domain = [
            'http://localhost:8000',
            'http://127.0.0.1:8000',
            'http://localhost:8080',
            'http://localhost:80'
        ];

//        header('content-type:application:json;charset=utf8');
//        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
//        $allow_origin = array(
//            'http://www.client.com',
//            'http://www.client2.com'
//        );
//        if(in_array($origin, $allow_origin)){
//            header('Access-Control-Allow-Origin:'.$origin);
//            header('Access-Control-Allow-Methods:POST');
//            header('Access-Control-Allow-Headers:x-requested-with,content-type');
//        }

        header("Access-Control-Allow-Origin: *");
        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin'
        ];
        if ($request->getMethod() === "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return \Response::make('OK', 200, $headers);
        }

        $response = $next($request);

        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
//        return $next($request);
    }
}
